package com.changgou.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.goods.feign.SkuFeign;
import com.changgou.order.config.RabbitMQConfig;
import com.changgou.order.dao.*;
import com.changgou.order.pojo.*;
import com.changgou.order.service.CartService;
import com.changgou.order.service.OrderService;
import com.changgou.pay.feign.PayFeign;
import com.changgou.util.IdWorker;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.time.LocalDate;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    /***
     * 查询全部列表
     * @return
     */
    @Override
    public List<Order> findAll() {
        return orderMapper.selectAll();
    }

    /***
     * 根据ID查询
     * @param id
     * @return
     */
    @Override
    public Order findById(String id) {
        return orderMapper.selectByPrimaryKey(id);
    }

    /***
     * 下单增加
     * @param order
     */
    @Autowired
    private CartService cartService;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SkuFeign skuFeign;
    @Autowired
    private TaskMapper taskMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    //购物车前缀
    private static final String CART = "cart_";

    @Override
    @Transactional
    //@GlobalTransactional(name = "order_add")
    public String add(Order order) {
        //1.获取购物车的相关信息(redis)
        Map map = cartService.list(order.getUsername());
        List<OrderItem> orderItemList = (List<OrderItem>) map.get("orderItemList");

        //2.统计计算:总金额,总数量
        Integer totalNum = (Integer) map.get("totalNum");
        Integer totalMoney = (Integer) map.get("totalMoney");

        //3.填充订单数据并保存到tb_order
        String orderId = idWorker.nextId() + "";
        order.setId(orderId);
        order.setTotalNum(totalNum);
        order.setTotalMoney(totalMoney);
        order.setPayMoney(totalMoney);
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        order.setBuyerRate("0"); //0.未评价 1.已评价
        order.setSourceType("1"); //1.web端 2.app 3.微信公众号 4.微信小程序 5.H5手机页面
        order.setOrderStatus("0");//0.未完成 1.已完成 2.已退货
        order.setPayStatus("0");//0.未支付 1.已支付
        order.setConsignStatus("0");//0.未发货 1.已发货 2.已送达
        order.setIsDelete("0"); //0.未删除 1.已删除

        orderMapper.insertSelective(order);

        //4.填充订单项数据并保存到tb_order_item
        for (OrderItem orderItem : orderItemList) {
            orderItem.setId(idWorker.nextId() + "");
            orderItem.setOrderId(orderId);
            orderItem.setIsReturn("0");//0.未退货 1.已退货

            orderItemMapper.insertSelective(orderItem);
        }

        //减库存
        //goods 减库存 (OrderItem)
        skuFeign.decrCount(order.getUsername());

        //int a = 1/0;

        //向任务表添加任务数据
        Task task = new Task();
        task.setCreateTime(new Date());
        task.setUpdateTime(new Date());
        task.setMqExchange(RabbitMQConfig.EX_BUYING_ADDPOINTUSER);
        task.setMqRoutingkey(RabbitMQConfig.CG_BUYING_ADDPOINT_KEY);

        Map paramMap = new HashMap();
        paramMap.put("orderId", orderId);
        paramMap.put("username", order.getUsername());
        paramMap.put("point", order.getPayMoney());
        task.setRequestBody(JSON.toJSONString(paramMap));
        taskMapper.insertSelective(task);

        //5.删除购物车数据
        redisTemplate.delete(CART + order.getUsername());

        //6.发送关闭订单的消息
        rabbitTemplate.convertAndSend("", "queue.ordercreate", order.getId());

        //7.返回订单id
        return order.getId();
    }


    /***
     * 修改
     * @param order
     */
    @Override
    //@GlobalTransactional(name = "order_update")
    public void update(Order order) {
        orderMapper.updateByPrimaryKey(order);
    }

    /***
     * 删除
     * @param id
     */
    @Override
    public void delete(String id) {
        orderMapper.deleteByPrimaryKey(id);
    }


    /***
     * 条件查询
     * @param searchMap
     * @return
     */
    @Override
    public List<Order> findList(Map<String, Object> searchMap) {
        Example example = createExample(searchMap);
        return orderMapper.selectByExample(example);
    }

    /***
     * 分页查询
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<Order> findPage(int page, int size) {
        PageHelper.startPage(page, size);
        return (Page<Order>) orderMapper.selectAll();
    }

    /***
     * 条件+分页查询
     * @param searchMap 查询条件
     * @param page 页码
     * @param size 页大小
     * @return 分页结果
     */
    @Override
    public Page<Order> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page, size);
        Example example = createExample(searchMap);
        return (Page<Order>) orderMapper.selectByExample(example);
    }

    /***
     * 修改订单状态为已支付
     * @param orderId
     * @param transactionId
     */

    @Autowired
    private OrderLogMapper orderLogMapper;

    @Override
    @Transactional
    public void updatePayStatus(String orderId, String transactionId) {
        //1.获取订单
        Order order = orderMapper.selectByPrimaryKey(orderId);

        //存在订单且状态为0
        if (order != null && order.getPayStatus().equals("0")) {
            //2.修改订单
            order.setPayStatus("1");
            order.setOrderStatus("1");//订单状态 已支付
            order.setUpdateTime(new Date());//更新时间
            order.setPayTime(new Date());//支付时间
            order.setTransactionId(transactionId);//微信交易流水号

            orderMapper.updateByPrimaryKeySelective(order);

            //3.记录订单变动日志
            OrderLog orderLog = new OrderLog();
            orderLog.setId(idWorker.nextId() + "");
            orderLog.setOperater("system");
            orderLog.setOperateTime(new Date());
            orderLog.setOrderId(orderId);
            orderLog.setOrderStatus("1");
            orderLog.setPayStatus("1");
            orderLog.setConsignStatus("0");
            orderLog.setRemarks("支付流水号:" + transactionId);

            orderLogMapper.insertSelective(orderLog);
        }
    }

    /***
     * 关闭订单
     * @param orderId
     */

    @Autowired
    private PayFeign payFeign;

    @Override
    @Transactional
    public void closeOrder(String orderId) {
        System.out.println("关闭订单开启：" + orderId);

        //1.根据id查询订单信息，判断订单是否存在，订单支付状态是否为未支付
        Order order = orderMapper.selectByPrimaryKey(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        if (!order.getPayStatus().equals("0")) {
            return;
        }
        System.out.println("开始关闭订单操作");

        //2.基于微信查询订单支付状态
        Map<String, String> queryMap = payFeign.queryOrder(orderId).getData();
        if (queryMap != null && queryMap.get("return_code").equals("SUCCESS")) {
            if ("SUCCESS".equals(queryMap.get("trade_code"))) {
                //2.1如果为success，则修改订单状态
                updatePayStatus(orderId, queryMap.get("transaction_id"));
                System.out.println("改为已支付");
            }
            //2.2如果为未支付，则修改订单，新增日志，恢复库存，关闭订单
            if ("NOTPAY".equals(queryMap.get("trade_state"))) {
                System.out.println("执行关闭");
                order.setOrderStatus("8");
                order.setUpdateTime(new Date());
                orderMapper.updateByPrimaryKeySelective(order);

                //2.3记录订单变动日志
                OrderLog orderLog = new OrderLog();
                orderLog.setId(idWorker.nextId() + "");
                orderLog.setOperater("system");
                orderLog.setOperateTime(new Date());
                orderLog.setOrderId(orderId);
                orderLog.setOrderStatus("8");
                orderLog.setPayStatus("0");
                orderLog.setConsignStatus("0");
                orderLog.setRemarks("微信未支付,关闭订单,支付流水号:" + queryMap.get("transaction_id"));
                orderLogMapper.insertSelective(orderLog);

                //恢复库存
                OrderItem orderItem = new OrderItem();
                orderItem.setOrderId(orderId);
                List<OrderItem> orderItems = orderItemMapper.select(orderItem);
                for (OrderItem item : orderItems) {
                    //每一个购物项都恢复库存
                    skuFeign.resumeStockNumCount(item.getSkuId(), item.getNum());
                }

                //关闭订单
                payFeign.closeOrder(orderId);
            }
            //生产环境中一个一个判断
            //if ("REFUND".equals(queryMap.get("trade_state"))){ }
            //if ("PAYERROR".equals(queryMap.get("trade_state"))){ }
        }
    }

    /***
     * 批量发货
     * @param orders
     */
    @Override
    @Transactional
    public void batchSend(List<Order> orders) {

        //1.判断每一个订单的运单号和物流公司的值是否存在
        for (Order order : orders) {
            if (order.getId() == null) {
                throw new RuntimeException("订单号为空");
            }
            if (order.getShippingCode() == null || order.getShippingName() == null) {
                throw new RuntimeException("请选择快递公司和填写快递单号");
            }
        }
        //2.循环订单,进行状态校验
        for (Order order : orders) {
            String orderId = order.getId();
            Order order1 = orderMapper.selectByPrimaryKey(orderId);
            if (!order1.getPayStatus().equals("1") || !order1.getOrderStatus().equals("1")) {
                throw new RuntimeException("订单状态有误！");
            }
        }
        //3.循环订单更新操作
        for (Order order : orders) {
            //3.1 order表
            order.setUpdateTime(new Date());
            order.setConsignTime(new Date());
            order.setOrderStatus("2");
            order.setConsignStatus("1");
            orderMapper.updateByPrimaryKeySelective(order);

            //3.2 orderLog表
            OrderLog orderLog = new OrderLog();
            orderLog.setId(idWorker.nextId() + "");
            orderLog.setOperater("卖家");
            orderLog.setOperateTime(new Date());
            orderLog.setOrderId(order.getId());
            orderLog.setOrderStatus("2");
            orderLog.setPayStatus("1");
            orderLog.setConsignStatus("1");
            orderLog.setRemarks("发货啦,商品正在路上");
            orderLogMapper.insertSelective(orderLog);
        }
    }

    /***
     * 手动确认收货
     * @param orderId
     * @param operator
     */
    @Override
    @Transactional
    public void confirmTask(String orderId, String operator) {
        if (orderId == null) {
            throw new RuntimeException("订单号不存在");
        }
        Order order = orderMapper.selectByPrimaryKey(orderId);
        //1.通过orderId 查询order对象是否存在
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        //2.判断order的状态是否为发货状态
        if (!order.getConsignStatus().equals("1")) {
            throw new RuntimeException("订单未发货");
        }

        //3.order的状态改为已收货
        order.setConsignStatus("2");//已送达
        order.setOrderStatus("3");//已完成
        order.setUpdateTime(new Date());
        order.setEndTime(new Date());
        orderMapper.updateByPrimaryKeySelective(order);

        //4.记录订单日志
        OrderLog orderLog = new OrderLog();
        orderLog.setId(idWorker.nextId() + "");
        orderLog.setOperater(operator);
        orderLog.setOperateTime(new Date());
        orderLog.setOrderId(order.getId());
        orderLog.setOrderStatus("3");
        orderLog.setPayStatus("1");
        orderLog.setConsignStatus("2");
        orderLog.setRemarks("已经收货啦");
        orderLogMapper.insertSelective(orderLog);
    }

    /***
     * 自动确认收货
     */

    @Autowired
    private OrderConfigMapper orderConfigMapper;

    @Override
    @Transactional
    public void autoTack() {
        //1.从订单配置表中获得到订单自动确认收货的时间点
        OrderConfig orderConfig = orderConfigMapper.selectByPrimaryKey(1);
        //获取当前时间
        LocalDate now = LocalDate.now();

        //2.从当前得到的时间点向前数(订单自动确认收货的时间节点)天,作为过期的时间节点
        LocalDate date = now.plusDays(-orderConfig.getTakeTimeout());

        //3.从订单表中获取符合相关条件的数据
        //按条件查询获取订单列表
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        //3.1.发货时间小于过期时间
        criteria.andLessThan("consignTime", date);
        //3.2.收货状态为未确认
        criteria.andEqualTo("orderStatus", "2");
        List<Order> orderList = orderMapper.selectByExample(example);

        //4.循环遍历,确认收货
        for (Order order : orderList) {
            this.confirmTask(order.getId(), "system");
        }
    }

    /***
     * 构建查询对象
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap) {
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        if (searchMap != null) {
            // 订单id
            if (searchMap.get("id") != null && !"".equals(searchMap.get("id"))) {
                criteria.andEqualTo("id", searchMap.get("id"));
            }
            // 支付类型，1、在线支付、0 货到付款
            if (searchMap.get("payType") != null && !"".equals(searchMap.get("payType"))) {
                criteria.andEqualTo("payType", searchMap.get("payType"));
            }
            // 物流名称
            if (searchMap.get("shippingName") != null && !"".equals(searchMap.get("shippingName"))) {
                criteria.andLike("shippingName", "%" + searchMap.get("shippingName") + "%");
            }
            // 物流单号
            if (searchMap.get("shippingCode") != null && !"".equals(searchMap.get("shippingCode"))) {
                criteria.andLike("shippingCode", "%" + searchMap.get("shippingCode") + "%");
            }
            // 用户名称
            if (searchMap.get("username") != null && !"".equals(searchMap.get("username"))) {
                criteria.andLike("username", "%" + searchMap.get("username") + "%");
            }
            // 买家留言
            if (searchMap.get("buyerMessage") != null && !"".equals(searchMap.get("buyerMessage"))) {
                criteria.andLike("buyerMessage", "%" + searchMap.get("buyerMessage") + "%");
            }
            // 是否评价
            if (searchMap.get("buyerRate") != null && !"".equals(searchMap.get("buyerRate"))) {
                criteria.andLike("buyerRate", "%" + searchMap.get("buyerRate") + "%");
            }
            // 收货人
            if (searchMap.get("receiverContact") != null && !"".equals(searchMap.get("receiverContact"))) {
                criteria.andLike("receiverContact", "%" + searchMap.get("receiverContact") + "%");
            }
            // 收货人手机
            if (searchMap.get("receiverMobile") != null && !"".equals(searchMap.get("receiverMobile"))) {
                criteria.andLike("receiverMobile", "%" + searchMap.get("receiverMobile") + "%");
            }
            // 收货人地址
            if (searchMap.get("receiverAddress") != null && !"".equals(searchMap.get("receiverAddress"))) {
                criteria.andLike("receiverAddress", "%" + searchMap.get("receiverAddress") + "%");
            }
            // 订单来源：1:web，2：app，3：微信公众号，4：微信小程序  5 H5手机页面
            if (searchMap.get("sourceType") != null && !"".equals(searchMap.get("sourceType"))) {
                criteria.andEqualTo("sourceType", searchMap.get("sourceType"));
            }
            // 交易流水号
            if (searchMap.get("transactionId") != null && !"".equals(searchMap.get("transactionId"))) {
                criteria.andLike("transactionId", "%" + searchMap.get("transactionId") + "%");
            }
            // 订单状态
            if (searchMap.get("orderStatus") != null && !"".equals(searchMap.get("orderStatus"))) {
                criteria.andEqualTo("orderStatus", searchMap.get("orderStatus"));
            }
            // 支付状态
            if (searchMap.get("payStatus") != null && !"".equals(searchMap.get("payStatus"))) {
                criteria.andEqualTo("payStatus", searchMap.get("payStatus"));
            }
            // 发货状态
            if (searchMap.get("consignStatus") != null && !"".equals(searchMap.get("consignStatus"))) {
                criteria.andEqualTo("consignStatus", searchMap.get("consignStatus"));
            }
            // 是否删除
            if (searchMap.get("isDelete") != null && !"".equals(searchMap.get("isDelete"))) {
                criteria.andEqualTo("isDelete", searchMap.get("isDelete"));
            }

            // 数量合计
            if (searchMap.get("totalNum") != null) {
                criteria.andEqualTo("totalNum", searchMap.get("totalNum"));
            }
            // 金额合计
            if (searchMap.get("totalMoney") != null) {
                criteria.andEqualTo("totalMoney", searchMap.get("totalMoney"));
            }
            // 优惠金额
            if (searchMap.get("preMoney") != null) {
                criteria.andEqualTo("preMoney", searchMap.get("preMoney"));
            }
            // 邮费
            if (searchMap.get("postFee") != null) {
                criteria.andEqualTo("postFee", searchMap.get("postFee"));
            }
            // 实付金额
            if (searchMap.get("payMoney") != null) {
                criteria.andEqualTo("payMoney", searchMap.get("payMoney"));
            }

        }
        return example;
    }

}
